import {
  getOssSignature,
  setOssSignature,
  getOssExpiration,
  setOssExpiration,
} from "@/config/storage.js";

import { service } from "@/config/request";

const OSSCONFIG = {
  accessKeyId: "LTAI5t7LzpHytxizVHqp63hs",
  accessKeySecret: "DGAaiWmsHVZ5Nu7shxxdJHp8Sceds3",
  bucketName: "building-d",
  endPoint: "oss-cn-hangzhou.aliyuncs.com",
};

// 获取uuid
export function guid() {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  return (
    S4() +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    S4() +
    S4()
  );
}

export async function upload(filePath) {
  let ossExpiration = getOssExpiration();
  if (new Date().getTime() > Number(ossExpiration)) {
    // 获取签名
    let data = await service({
      path: "/pigx-mall/direct/signature",
      method: "POST",
      data: {},
    });
    console.log(data,123);
    setOssSignature(data);
    setOssExpiration(data.expire);
  }
  const { policy, signature, dir } = getOssSignature();
  const pathName = dir + "/" + guid() + ".png";
  return new Promise((resolve) => {
    uni.uploadFile({
      url: process.env.OSS_URL,
      filePath: filePath,
      name: "file",
      header: {
        "Content-Type": "multipart/form-data",
      },
      formData: {
        key: pathName,
        policy,
        OSSAccessKeyId: OSSCONFIG.accessKeyId,
        success_action_status: "200",
        signature,
      },
      success: (res) => {
        const url = `${process.env.OSS_URL}/${pathName}`;
        resolve(url);
      },
      fail: (err) => {
        console.log(err);
      },
    });
  });
}
